package top.meeting.room.common.kit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * Created by Lyt on 2017/9/13.
 */
public class HttpKit {
    private static final Logger _log = LoggerFactory.getLogger(HttpKit.class);

    private static String ConvertStream2Json(InputStream inputStream) {
        String jsonStr = "";
        // ByteArrayOutputStream相当于内存输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        // 将输入流转移到内存输出流中
        try {
            while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, len);
            }
            // 将内存流转换为字符串
            jsonStr = new String(out.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        _log.debug("The http response body is: {}", jsonStr);
        return jsonStr;
    }

    private static HttpClient getClient() {
        HttpClient client = new HttpClient();
        HttpConnectionManagerParams cmp = client.getHttpConnectionManager().getParams();
        cmp.setConnectionTimeout(5000); //连接超时
        cmp.setSoTimeout(5000); //读取数据超时
        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        return client;
    }

    public static String doGetStr(String url) {
        HttpClient client = getClient();
        GetMethod get = new GetMethod(url);

        HttpMethodParams params = new HttpMethodParams();
        get.setParams(params);

        try {
            int statusCode = client.executeMethod(get);
            if (statusCode == HttpStatus.SC_OK) {
                //return get.getResponseBodyAsString();
                InputStream is = get.getResponseBodyAsStream();
                return ConvertStream2Json(is);
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String doPost(String url, Map<String, String> param) {

        HttpClient httpClient = getClient();
        PostMethod method = new PostMethod(url);

        try {


            httpClient.getParams().setContentCharset("UTF-8");

            method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
            NameValuePair[] data = null;

            if (param != null && param.size() > 0) {
                data = new NameValuePair[param.size()];
                int index = 0;
                for (Map.Entry<String, String> current : param.entrySet()) {
                    data[index] = new NameValuePair(current.getKey(), current.getValue());
                    index++;
                }
                method.setRequestBody(data);
            }
            HttpClientParams httparams = new HttpClientParams();
            //模拟浏览器提交
            httparams.setParameter(HttpMethodParams.USER_AGENT, "Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.2) Gecko/20090803 Fedora/3.5.2-2.fc11 Firefox/3.5.2");
            method.setParams(httparams);
            httpClient.executeMethod(method);
            return method.getResponseBodyAsString();

        } catch (Exception e) {
            e.printStackTrace();

            _log.error("error:" + e.toString());

        } finally {
            if (method != null) {
                method.releaseConnection();
                method = null;
            }
            if (httpClient != null) {
                httpClient = null;
            }
        }

        return null;

    }

    public static JSONObject doGetJson(String url) {
        return JSON.parseObject(doGetStr(url));
    }
}
